<template>
  <div class="app-container" v-loading="pageLoading">
    <!-- <el-button type="primary" class="fr" @click="createItem" v-record="{doing:'点击了创建'}" v-permission="'warehouse.add'">
      创建</el-button> -->
    <div class="flex" style="justify-content: space-between;align-items: center;">
      <div class="filter-container" id="seachview">
        <el-select class="filter-item" style="width: 220px" @change="changeWh" v-model="query.warehouse_id"
          placeholder="选择仓库" clearable>
          <el-option v-for="i in whOptions" :key="i.key" :label="i.value" :value="i.key"></el-option>
        </el-select>
        <el-select class="filter-item" style="width: 140px" v-model="query.rack_id" placeholder="选择货架" clearable>
          <el-option v-for="i in rackOptions" :key="i.key" :label="i.value" :value="i.key"></el-option>
        </el-select>
        <el-select class="filter-item" placeholder="输入料号搜索" style="width: 220px" v-model="query.material_id" filterable
          remote :remoteMethod="getSkuOptions" clearable>
          <el-option v-for="item in matOptions" :key="item.key" :value="item.key" :label="item.value"></el-option>
        </el-select>
        <el-button class="filter-item" type="success" plain @click="getList">查询</el-button>
        <div class="ml-40 flex" style="align-items: center;"></div>
      </div>
      <div class="filter-container flex">
        <span>所有货架:</span>
        <el-link type="primary" class="m-5" v-for="(i, t) in rackOptions" :key="t" @click="jumpRack(i)">{{
          i.label }}
        </el-link>
      </div>
    </div>
    <div class="ml-10 mt-15 flex " style="justify-content: space-between;align-items: center;" v-if="list.length">
      <div class="flex">
        <div v-for="(i, t) in legend" :key="t" style="align-items:center" class="flex mr-10">
          <div style="width:10px;height:10px;border-radius:2px" :style="{ background: i.bgc }"></div>
          <div>{{ i.name }}</div>
        </div>
      </div>
      <div class="flex">
        <span style="font-weight:700">总数：{{ stock_total }} </span>
        <span style="margin-left:20px;font-weight:700">货物：{{ stock_inventory }} </span>
        <span style="margin-left:20px;font-weight:700">容器：{{ stock_pallet }} </span>
        <span style="margin-left:20px;font-weight: 700;">空闲: {{ stock_remaind }} </span>
      </div>
      <div class="flex" style="align-items:center">
        <div class="flex" style="align-items:center">
          <span class="mr-10">仓库库位使用:</span>
          <el-progress text-color="#000000" style="width:120px" :text-inside="true" :stroke-width="26"
            :percentage="warehouse_percent">
            {{ warehouse_percent }}%
          </el-progress>
        </div>
      </div>
    </div>
    <div style="width:100%;overflow-x:scroll;" v-if="list.length">
      <div class="p-10" style="width:100%;border-bottom: 4px double #ccc;" v-for="(item, index) in list" :key="index">
        <div class="flex mt-10">
          <span style="font-size:20px;font-weight:700" :id="item.RackName">{{ item.RackName }}</span>
          <div class="flex ml-20" style="align-items:center">
            <span class="mr-10">货架库位使用:</span>
            <el-progress text-color="#000000" style="width:120px" :text-inside="true" :stroke-width="24"
              :percentage="Number(item.RackPercent)" status="success">
            </el-progress>
          </div>
        </div>
        <div class="flex" style="align-items:center;">
          <div class="level-title"></div>
          <div class="flex-col m-2" style="align-items:center;flex-wrap: nowrap;" v-for="(ii, tt) in item.MaxColumn"
            :key="tt">
            <div class="stock-div col-title">{{ ii }}</div>
          </div>
        </div>
        <div class="flex" style="align-items:center;" v-for="(i, t) in item.MaxRow" :key="t">
          <div class="level-title">{{ item.MaxRow + 1 - i }}层</div>
          <div class="flex-col m-2" style="align-items:center;flex-wrap: nowrap;"
            v-for="(ii, tt) in item.StockList.filter(ii => ii.Level == item.MaxRow + 1 - i)" :key="tt">
            <div @click="seeDetail(ii)" class="stock-div pointer" :class="ii.status == 3 ? 'error' : ''"
              :style="{ background: setbgColor(ii) }">
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>
      <el-empty description="请选择仓库进行查询"></el-empty>
    </div>
    <div class="backTop" title="返回顶部" v-if="scrollTop > 200">
      <el-button @click="jumpRack({ label: 'seachview' })" type="warning" size="medium " :icon="CaretTop" circle>
      </el-button>
    </div>
    <el-dialog :close-on-click-modal="false" title="库位明细" v-model="showStockFlag" width="80%">
      <z-Table :list="detailList" :tableProps="tableProps" :columns="columns"></z-Table>
      <div class="mt-30" v-if="detailList.length > 0">
        <el-row>
          <el-col :span="12" class="flex flex-center">
            <el-button type="primary" plain @click="showPositionChoose = !showPositionChoose">下架</el-button>
            <span v-if="showPositionChoose" class="ml-40">选择目的点位：</span>
            <el-radio-group class="ml-10" v-if="showPositionChoose" v-model="positionId">
              <el-radio-button v-for="i in positionOptions" :key="i.PositionId" :value="i.PositionId">{{ i.PositionCode
                }}</el-radio-button>
            </el-radio-group>
            <el-button class="ml-30" :loading="btnLoading" v-if="showPositionChoose" @click="doPullOff"
              type="success">提交</el-button>
          </el-col>
          <el-col :span="12" class="flex flex-center">
            <el-button type="primary" plain @click="showYiweiChoose = !showYiweiChoose">移位</el-button>
            <span v-if="showYiweiChoose" class="ml-20">选择目标库位：</span>
            <el-select class="ml-10" filterable style="width: 180px" v-if="showYiweiChoose"
              v-model="yiweiObj.dest_stock_id" clearable>
              <el-option v-for="i in stockOptions" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>
            <el-button class="ml-10" :loading="btnLoading" v-if="showYiweiChoose" @click="doYiwei"
              type="success">提交</el-button>
          </el-col>
        </el-row>
      </div>
      <template #footer>
        <span>
          <el-button @click="showStockFlag = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  CaretTop
} from '@element-plus/icons-vue'
</script>

<script>
import commonMixin from '@/views/_common/mixin'
import zTable from '@/views/_common/table.vue'
export default {
  mixins: [commonMixin],
  name: 'WmsStockInventory',
  components: { zTable },
  data: function () {
    return {
      api: this.$api.wInventoryDetail,
      warehouse_percent: 0,
      rack_percent: 0,
      whOptions: [],
      tableProps: {
        border: true,
        opsColWith: 100,
        hideOperations: true,
      },
      scrollTop: 0, // 页面滚动高度
      columns: [
        { title: '库位编码', key: 'StockCode', width: 140 },
        { title: '物料编码', key: 'MaterialCode', width: 130 },
        { title: '物料名称', key: 'MaterialName', width: 150 },
        { title: '数量', key: 'Qty', width: 100 },
        { title: '批次号', key: 'LotNo', width: 100 },
        { title: '托盘号', key: 'ContainerCode', width: 100 },
        { title: '条码', key: 'Sn' },
        { title: '入库日期', key: 'LotDateCode', width: 120 }
      ],
      detailList: [],
      rackOptions: [],
      layerOptions: [],
      legend: [
        { name: '有货', bgc: '#7300e6', value: 1 },
        { name: '容器', bgc: '#094fe6', value: 6 },
        { name: '无货', bgc: '#bbbbbb', value: 0 },
        { name: '锁定', bgc: '#a40f11', value: 2 },
        { name: '下架中', bgc: '#e6e46e', value: 4 },
        { name: '上架中', bgc: '#31a75a', value: 5 },
        { name: '按物料查询', bgc: '#74e20d', value: 7 },
        { name: '', bgc: '#ffffff', value: 3 },
      ],
      curStock: {},
      showStockFlag: false,
      list: [],
      showMax: 0,
      query: {
        warehouse_id: null,
        rack_id: null,
      },
      stock_total: null,
      stock_remaind: null,
      stock_inventory: null,
      stock_pallet: null,
      stock_percent: null,
      curPos: 'seachview', // 当前滚动位置
      queryDetail: {
        page: 1,
        size: 10,
        queryString: {
          stock_code: null,
        },
      },
      showPositionChoose: false,
      positionId: null,
      positionOptions: [],
      btnLoading: false,
      matOptions: [],
      showYiweiChoose: false,
      yiweiObj: {},
      tickForTimeout: null,
    }
  },
  computed: {
    stockOptions: function () {
      let tmp = []
      this.list.forEach((x) => {
        tmp.push(
          ...(x.StockList || [])
            .filter((i) => i.Status == 0)
            .map((i) => ({
              label: i.StockCode,
              value: i.StockId,
            })),
        )
      })
      return tmp
    },
  },
  methods: {
    getSkuOptions(query) {
      this.matOptions = []
      if (query) {
        this.http.post('/api/Bas_Material/getPageData', {
          page: 1,
          rows: 200,
          sort: 'MaterialCode',
          order: 'asc',
          wheres: JSON.stringify([
            { name: 'MaterialCode', value: query, displayType: 'like' }
          ])
        }).then(r => {
          this.matOptions = this.arrayOptions(r.rows, 'MaterialId', ['MaterialCode', 'MaterialName'])
        })
      }
    },
    jumpRack(i) {
      this.curPos = i.label
      let cur = document.getElementById(i.label)
      this.$nextTick(() => {
        cur.scrollIntoView({
          behavior: 'smooth', // 平滑过渡
          block: 'start', // 上边框与视窗顶部平齐。默认值
        })
      })
    },
    setbgColor(item) {
      let leg = this.legend.find((x) => x.value == item.Status)
      if (leg) return leg.bgc
      return ''
    },
    seeDetail(item) {
      this.curStock = item
      this.queryDetail.StockId = item.StockId
      this.queryDetail.WarehouseId = this.query.warehouse_id
      if (item.StockCode) {
        this.getDetailList()
      } else {
        this.$message.error('当前位置无库位')
      }
    },
    getDetailList() {
      this.http.post(this.$api.wmsCommon + 'GetInvDetail', {
        ...this.queryDetail
      }).then(r => {
        this.showStockFlag = true
        this.showPositionChoose = false
        this.detailList = r
      })
    },
    changeWh() {
      this.query.rack_id = null
      this.list = []
      localStorage.setItem('WmsStockInventory', JSON.stringify(this.query))
      this.getRackOptions()
      this.getPositionOptions()
    },
    getRackOptions() {
      this.http.post('/api/Wms_Rack/getPageData', {
        page: 1,
        rows: 9999,
        sort: 'RackCode',
        order: 'asc',
        wheres: JSON.stringify([
          { name: 'WarehouseId', value: this.query.warehouse_id }
        ])
      }).then(r => {
        this.rackOptions = this.arrayOptions(r.rows, 'RackId', 'RackCode')
      })
    },
    getPositionOptions() {
      this.http.post('/api/Wms_Position/getPageData', {
        page: 1,
        rows: 9999,
        sort: 'PositionCode',
        order: 'asc',
        wheres: JSON.stringify([
          { name: 'WarehouseId', value: this.query.warehouse_id },
          { name: 'IsStockOutPort', value: 1 }
        ])
      }).then(r => {
        this.positionOptions = r.rows
      })
    },
    getList(noLoading) {
      localStorage.setItem('WmsStockInventory', JSON.stringify(this.query))
      if (!this.query.warehouse_id) {
        return this.$message.error('请选择仓库或者货架')
      }
      if (!noLoading) this.pageLoading = true
      this.http.post('/api/Wms_Inventory/GetStockInventory', {
        WarehouseId: this.query.warehouse_id,
        RackId: this.query.rack_id,
        MaterialId: this.query.material_id
      }).then((r) => {
        this.list = r.RackList
        this.showMax = r.Max
        this.stock_total = r.StockTotal
        this.stock_remaind = r.StockRemainder
        this.stock_inventory = r.StockWithGoods
        this.stock_pallet = r.StockWithContainer
        this.warehouse_percent = Number(r.WarehousePercent)
        if (this.tickForTimeout != null) {
          clearTimeout(this.tickForTimeout)
        }
        this.tickForTimeout = setTimeout(() => {
          this.getList(true)
        }, 10000)
      })
        .finally(() => {
          if (!noLoading) this.pageLoading = false
        })
    },
    doPullOff() {
      if (!this.positionId || this.positionId == 0) {
        return this.$message.error('未选择目的点位')
      }
      this.$confirm('确定对当前货位执行下架？').then(() => {
        this.btnLoading = true
        this.http.post(this.$api.wmsPullOff + 'PullOffCommit', {
          WarehouseId: this.query.warehouse_id,
          List: this.detailList.map(x => ({
            ContainerCode: x.ContainerCode,
            FromStockId: x.StockId,
            PositionId: this.positionId,
          }))
        }).then((r) => {
          this.$message.success('下发任务成功')
          this.showStockFlag = false
        })
          .finally(() => {
            this.btnLoading = false
          })
      })
    },
    doYiwei() {
      if (!this.yiweiObj.dest_stock_id) {
        return this.$message.success('未选择目的库位')
      }
      this.$confirm('确定执行移库操作？').then(() => {
        this.btnLoading = true
        this.http.post(this.$api.wmsPullOff + 'MoveStockCommit', {
          WarehouseId: this.query.warehouse_id,
          FromStockId: this.detailList[0].StockId,
          DestStockId: this.yiweiObj.dest_stock_id,
          ContainerCode: this.detailList[0].ContainerCode,
        })
          .then((r) => {
            this.$message.success('创建移库任务成功')
            this.showStockFlag = false
            this.yiweiObj.dest_stock_id = null
          })
          .finally(() => {
            this.btnLoading = false
          })
      })
    },
    handleScroll(e) {
      this.scrollTop = e.target.scrollTop
    },
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    this.http.post('/api/Wms_Warehouse/getPageData', {
      page: 1,
      rows: 9999,
      sort: 'WarehouseCode',
      order: 'asc',
      wheres: JSON.stringify([])
    }).then(r => {
      this.whOptions = this.arrayOptions(r.rows, 'WarehouseId', ['WarehouseCode', 'WarehouseName'])
    })

    let obj = JSON.parse(localStorage.getItem('WmsStockInventory'))
    if (!!obj) {
      this.query = { warehouse_id: obj.warehouse_id }
      if (!!obj.warehouse_id) {
        this.changeWh()
        this.getList()
      }
    }
  },
  created: function () { },
  beforeDestroy: function () {
    if (this.tickForTimeout) clearTimeout(this.tickForTimeout)
  },
  deactivated: function () {
    if (this.tickForTimeout) clearTimeout(this.tickForTimeout)
  },
  activated: function () {
    if (this.query.WarehouseId > 0) this.getList()
  },
}
</script>
<style scoped>
.error {
  border: 1px solid #ff0228;
}

.backTop {
  position: fixed;
  right: 30px;
  bottom: 50px;
}

.level-title {
  min-width: 40px;
  height: 30px;
  line-height: 30px;
}

.col-title {
  min-width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  flex-wrap: nowrap;
}

.stock-div {
  border-radius: 4px;
  width: 30px;
  height: 30px;
  padding: 2px;
}
</style>
